load("@rules_motoko//motoko:defs.bzl", "external_actor")
load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_test")
load("//bazel:canisters.bzl", "motoko_canister")

package(default_visibility = ["//visibility:public"])

# The motoko compiler fails to map float types in the Governance init arg to
# appropriate Motoko types.
genrule(
    name = "patch_governance.did",
    srcs = [
        "//rs/nns/governance:canister/governance.did",
    ],
    outs = ["patched_governance.did"],
    cmd_bash = """
    cat $(location //rs/nns/governance:canister/governance.did) | sed 's|service : (Governance) -> |service : |g' > $@
""",
    visibility = ["//visibility:private"],
)

genrule(
    name = "patch_root.did",
    srcs = [
        "//rs/nns/handlers/root/impl:canister/root.did",
    ],
    outs = ["patched_root.did"],
    cmd_bash = """
    cat $(location //rs/nns/handlers/root/impl:canister/root.did) | sed 's|service : () -> |service : |g' > $@
""",
    visibility = ["//visibility:private"],
)

external_actor(
    name = "governance",
    idl = ":patched_governance.did",
    principal = "rrkah-fqaaa-aaaaa-aaaaq-cai",
    visibility = ["//visibility:private"],
)

external_actor(
    name = "root",
    idl = ":patched_root.did",
    principal = "r7inp-6aaaa-aaaaa-aaabq-cai",
    visibility = ["//visibility:private"],
)

motoko_canister(
    name = "lifeline_canister",
    entry = "lifeline.mo",
    moc_flags = [
        # The lifeline canister has no stable variables so we use the classical orthogonal persistence
        # with 32bit main memory such that upgrades don't require the wasm_memory_persistence option.
        "--legacy-persistence",
    ],
    deps = [
        # Keep sorted.
        ":governance",
        ":root",
    ],
)

rust_library(
    name = "lifeline",
    srcs = ["src/lib.rs"],
    compile_data = [":lifeline_canister"],
    rustc_env = {
        "LIFELINE_CANISTER_WASM_PATH": "$(location :lifeline_canister)",
    },
)

rust_binary(
    name = "lifeline_bin",
    srcs = ["src/main.rs"],
    deps = [":lifeline"],
)

rust_test(
    name = "lifeline_unit_test",
    compile_data = [":lifeline_canister.wasm.gz"],
    crate = ":lifeline",
    deps = [
        # Keep sorted.
        "@crate_index//:flate2",
        "@crate_index//:wasmprinter",
    ],
)
